package com.zzyl.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.NursingProjectDto;
import com.zzyl.entity.NursingProject;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.NursingProjectMapper;
import com.zzyl.service.NursingProjectService;
import com.zzyl.vo.NursingProjectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class NursingProjectServiceImpl implements NursingProjectService {

    @Autowired
    private NursingProjectMapper nursingProjectMapper;

    @Override
    public NursingProjectVo selectById(Integer id) {
        NursingProjectVo nursingProjectVo  = nursingProjectMapper.selectById(Long.valueOf(id));
        return nursingProjectVo;
    }

    @Override
    public void updateNursingProject(NursingProjectDto nursingProjectDto) {
        try {
            // 将dto转成entity
            NursingProject nursingProject = BeanUtil.toBean(nursingProjectDto, NursingProject.class);
            nursingProjectMapper.updateById(nursingProject);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.NURSING_PROJECT_UPDATE_FAIL);
        }
    }

    @Override
    public void insertNursingProject(NursingProjectDto nursingProjectDto) {
        try {
            // 将dto转成entity
            NursingProject nursingProject = BeanUtil.toBean(nursingProjectDto, NursingProject.class);
            nursingProjectMapper.insert(nursingProject);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.NURSING_PROJECT_INSERT_FAIL);
        }
    }

    @Override
    public PageResponse selectByPage(String name, Integer status,
                                     Integer pageNum, Integer pageSize) {
        // 使用分页插件
        PageHelper.startPage(pageNum, pageSize);
        Page<NursingProjectVo> page = nursingProjectMapper.selectByPage(name, status);
        PageResponse<NursingProjectVo> of = PageResponse.of(page, NursingProjectVo.class);
        of.getRecords().forEach(vo -> {
            Long count = nursingProjectMapper.getProjectRefCount(vo.getId());
            // 设置每一个护理项目被引用的次数
            vo.setCount(count);
        });
        return of;
    }
}
